package cn.pengpeng.day05.friends;

import java.io.IOException;
import java.util.Arrays;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class CommonFriendsTwo {
	
	public static class CommonFriendsTwoMapper extends Mapper<LongWritable, Text, Text, Text>{
		
		@Override
		protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, Text>.Context context)
				throws IOException, InterruptedException {
			
			// A	I,K,C,B,G,F,H,O,D,
			String[] split = value.toString().split("\t");
			String f = split[0];
			String[] users = split[1].split(",");
			Arrays.sort(users);
			
			for(int i=0;i<users.length-1;i++) {
				for(int j=i+1;j<users.length;j++) {
					context.write(new Text(users[i]+"-"+users[j]), new Text(f));
				}
				
			}
		}
		
		
	}
	
	public static class CommonFriendsTwoReducer extends Reducer<Text, Text, Text, Text>{
		
		@Override
		protected void reduce(Text userPair, Iterable<Text> friends, Reducer<Text, Text, Text, Text>.Context context)
				throws IOException, InterruptedException {
			
			StringBuilder sb = new StringBuilder();
			for (Text f : friends) {
				sb.append(f.toString()).append(",");
			}
			
			context.write(userPair, new Text(sb.deleteCharAt(sb.length()-1).toString()));
		}
		
		
	}
	
	
	public static void main(String[] args) throws Exception {

		Configuration conf = new Configuration(); // 会自动加载运行时classpath中的Hadoop配置文件

		Job job = Job.getInstance(conf);

		job.setJarByClass(CommonFriendsTwo.class);

		job.setMapperClass(CommonFriendsTwoMapper.class);
		job.setReducerClass(CommonFriendsTwoReducer.class);

		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(Text.class);

		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(Text.class);

		Path path = new Path(args[1]);
		FileSystem fs = FileSystem.get(conf);
		if (fs.exists(path)) {
			fs.delete(path, true);
		}

		FileInputFormat.setInputPaths(job, new Path(args[0]));
		FileOutputFormat.setOutputPath(job, path);

		job.setNumReduceTasks(1);

		boolean res = job.waitForCompletion(true);
		System.exit(res ? 0 : 1);

	}
	

}
